﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CDude.Vita
{
    internal static class VitaCOMgui
    {
        private static readonly Version APP_VERSION = Assembly.GetExecutingAssembly().GetName().Version;
        private const string ERROR_OUT_FILE_PATH = "error_log_gui.txt";

        private static void CheckForUpdates()
        {
            WebClient webclient = new WebClient();
            try
            {
                string str_latestversion = webclient.DownloadString("http://data.celcodioc.host22.com/vitacom/latest_version");

                int[] latestversion = new int[2] { Convert.ToInt32(str_latestversion.Substring(0, str_latestversion.IndexOf('.'))), Convert.ToInt32(str_latestversion.Substring(2)) };
                if (latestversion[0] > APP_VERSION.Major || (latestversion[0] >= APP_VERSION.Major && latestversion[1] > APP_VERSION.Minor))
                {
                    DialogResult dialogresult = MessageBox.Show("Version " + str_latestversion + " is available. Do you want to download it now?", "Update — VitaCOMgui", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
                    if (dialogresult == DialogResult.Yes)
                        Process.Start("http://code.google.com/p/vitacom/downloads/list");
                }
            }
            catch { }
            finally
            {
                webclient.Dispose();
            }
        }

        [STAThread]
        private static void Main()
        {
            new Task(() => { CheckForUpdates(); }).Start();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new VCg_MainForm());
        }

        //Save exception data to a file
        private static void SaveException(Exception ex)
        {
            try
            {
                string sout = ex.Message + "\r\n" + ex.StackTrace;
                using (StreamWriter sw = new StreamWriter(ERROR_OUT_FILE_PATH))
                    sw.Write(sout);

                MessageBox.Show("Saved stack trace to " + ERROR_OUT_FILE_PATH + "!", "Exception caught – VitaCOMgui", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception exx)
            {
                MessageBox.Show("Could not save stack trace to file!\n\n" + exx.Message + "\n" + exx.StackTrace, "Exception caught – VitaCOMgui", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}